package com.hiyee.goods.service.impl;

import com.hiyee.goods.mapper.CategoryMapper;
import com.hiyee.goods.service.CategoryService;
import com.hiyee.pojo.GoodsCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper goodsCategoryMapper;

    @Override
    public Map<String, Object> getH5Tree() {
        Map<String, Object> category = new HashMap<>();
        // 查询所有分类
        Example example = new Example(GoodsCategory.class);
        Example.Criteria criteria = example.createCriteria();
        // 查询一级分类
        GoodsCategory goodsCategory = goodsCategoryMapper.selectByPrimaryKey(1);
        if(goodsCategory == null)return category;
        category.put("id", goodsCategory.getCategoryId());
        category.put("name", goodsCategory.getName());
        // 查询二级分类
        criteria.andEqualTo("parentId", goodsCategory.getCategoryId()).andEqualTo("isActive", 1);
        example.setOrderByClause("sort_num asc");
        List<GoodsCategory> level2List = goodsCategoryMapper.selectByExample(example);
        if(level2List.isEmpty())return category;
        List<Map<String, Object>> child2List = new ArrayList<>();
        category.put("children", child2List);
        for (GoodsCategory level2 : level2List) {
            Map<String, Object> child2 = new HashMap<>();
            child2.put("id", level2.getCategoryId());
            child2.put("name", level2.getName());
            child2.put("pid", level2.getParentId());
            child2.put("image", level2.getIconUrl());
            List<Map<String, Object>> child3List = new ArrayList<>();
            child2.put("children", child3List);
            // 查三级分类
            Example example2 = new Example(GoodsCategory.class);
            Example.Criteria criteria2 = example2.createCriteria();
            criteria2.andEqualTo("parentId", level2.getCategoryId()).andEqualTo("isActive", 1);
            example2.setOrderByClause("sort_num asc");
            List<GoodsCategory> level3List = goodsCategoryMapper.selectByExample(example2);

            for (GoodsCategory level3 : level3List) {
                Map<String, Object> child3 = new HashMap<>();
                child3.put("id", level3.getCategoryId());
                child3.put("name", level3.getName());
                child3.put("pid", level3.getParentId());
                child3.put("image", level3.getIconUrl());
                child3List.add(child3);
            }
            child2List.add(child2);
        }
        return category;
    }
}
